<template>
  <div class="avatar-uploader-warp">
    <el-upload
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      class="avatar-uploader"
      action="https://jsonplaceholder.typicode.com/posts/">
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon"/>
    </el-upload>
    <span>{{ tips }}</span>
  </div>
</template>

<script>
export default {
  props: {
    imgUrl: {
      type: String,
      default: ''
    },
    tips: {
      type: String,
      default: ''
    }
  },
  data() {
    return {

    }
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload: function(file) {
      const type = file.type
      var isImage = true
      debugger
      if (type !== 'image/jpeg' && type !== 'image/png') {
        this.$message.error('上传头像图片只能是 JPG,PNG 格式!')
        isImage = false
      }

      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isImage && isLt2M
    }
  }
}
</script>

<style>
  .avatar-uploader-warp{
    width: 100%;
    display: flex;
    margin: 10px;
    flex-flow: column;
    align-items: center;
  }
  .avatar-uploader-warp .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 60%;
    width: 80px;
    height: 80px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader-warp .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100%;
    height: 100%;
    line-height: 80px;
    text-align: center;
  }
  .avatar {
    width: 100%;
    height: 100%;
    display: block;
  }
</style>
